package com.hk.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hk.context.BaseContext;
import com.hk.core.PageResult;

import com.hk.domain.Business;

import com.hk.domain.TalkHistory;
import com.hk.dto.*;
import com.hk.mapper.BusinessMapper;

import com.hk.mapper.TalkHistoryMapper;
import com.hk.service.BusinessService;
import com.hk.vo.TalkHistoryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper,Business> implements BusinessService {
    @Autowired
    BusinessMapper businessMapper;
    @Autowired
    TalkHistoryMapper talkHistoryMapper;

    public static final Integer TRUE=1;
    public static final Integer TRUEING=2;
    public static final Integer CHANGE=0;
    public static final Integer T=0;
    public static final Integer F=1;

    //商机列表展示
    @Override
    public PageResult list(BusinessPageDto dto) {
        Page<Business> page = new Page<>(dto.getPageNum(), dto.getPageSize());


        Page<Business> p = businessMapper.selectPage(page, Wrappers.<Business>lambdaQuery()
                .in(Business::getStatus,  TRUE, TRUEING).
                eq(Business::getAuthenticity, T)
                .like(ObjectUtils.isNotEmpty(dto.getId()),Business::getId,dto.getId())
                .like(ObjectUtils.isNotEmpty(dto.getName()), Business::getName, dto.getName())
                .like(StringUtils.isNotBlank(dto.getPhone()), Business::getPhone, dto.getPhone()).
                like(StringUtils.isNotBlank(dto.getOwner()), Business::getOwner, dto.getOwner()).
                like(ObjectUtils.isNotEmpty(dto.getStatus()), Business::getStatus, dto.getStatus()).apply(hasDateRange(dto),
                        "DATE_FORMAT(create_time, '%Y-%m-%d') BETWEEN DATE_FORMAT({0}, '%Y-%m-%d') AND DATE_FORMAT({1}, '%Y-%m-%d')",
                        dto.getParams().get("beginCreateTime"),
                        dto.getParams().get("endCreateTime")));


        PageResult pageResult = new PageResult();
        pageResult.setCode(200);
        pageResult.setTotal((int) p.getTotal());
        pageResult.setRows(p.getRecords());
        pageResult.setMsg("认证成功");
        return pageResult;
    }

    /**
     * 添加商机
     * @param business
     */
    @Override
    public void add(Business business) {
        business.setOwner(BaseContext.getCurrent().getUserName());
        business.setStatus(TRUE);
        businessMapper.insert(business);

    }

    /**
     * 根据id查看商机表
     * @param id
     * @return
     */
    @Override
    public Business queryById(Integer id) {
        Business business = businessMapper.selectById(id);
        return business;
    }

    /**
     * 根据id查看历史记录
     * @param businessId
     */
    @Override
    public List<TalkHistoryVo> queryTalkById(Integer businessId) {
        List<TalkHistory> talkHistories = talkHistoryMapper.selectList(Wrappers.<TalkHistory>lambdaQuery().eq(TalkHistory::getBusinessId, businessId));
        List<TalkHistoryVo> talkHistoryVos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(talkHistories)){
            for (TalkHistory i : talkHistories) {
                TalkHistoryVo talkHistoryVo = new TalkHistoryVo();
                String[] ignoreProperties = {"keys"};
                BeanUtils.copyProperties(i, talkHistoryVo, ignoreProperties);
                if (StringUtils.isNotBlank(i.getKeys())){
                    String keys = i.getKeys();
                    String[] arr = keys.split(",");
                    talkHistoryVo.setKeys(arr);
                }
                talkHistoryVos.add(talkHistoryVo);
            }
        }
        return talkHistoryVos;
    }

    /**
     * 更新商机表同时新增沟通记录
     * @param
     */
    @Override
    public void update(BusinessUpdateDto dto) {
        Business business = new Business();
        TalkHistory talkHistory = new TalkHistory();
        BeanUtils.copyProperties(dto,business);
        BeanUtils.copyProperties(dto,talkHistory);
        business.setId(dto.getBusinessId().longValue());
        business.setStatus(TRUEING);
        businessMapper.updateById(business);
        talkHistoryMapper.insert(talkHistory);
    }

    //推到公海池
    @Override
    public Integer push(Integer businessId, Integer id) {
        int num = businessMapper.update(Wrappers.<Business>lambdaUpdate().set(Business::getReasons, id)
                .set(Business::getAuthenticity, F).eq(Business::getId, id));
        return num;
    }

    //查询公海池
    @Override
    public PageResult listFalse(BusinessFalsePageDto dto) {
        Page<Business> page = new Page<>(dto.getPageNum(), dto.getPageSize());


        Page<Business> p = businessMapper.selectPage(page, Wrappers.<Business>lambdaQuery()
                .eq(Business::getAuthenticity, F)
                .like(ObjectUtils.isNotEmpty(dto.getName()), Business::getName, dto.getName())
                .like(StringUtils.isNotBlank(dto.getPhone()), Business::getPhone, dto.getPhone()).
                like(ObjectUtils.isNotEmpty(dto.getSubject()), Business::getSubject, dto.getSubject()).
                like(ObjectUtils.isNotEmpty(dto.getId()), Business::getId, dto.getId()).apply(DateRange(dto),
                        "DATE_FORMAT(create_time, '%Y-%m-%d') BETWEEN DATE_FORMAT({0}, '%Y-%m-%d') AND DATE_FORMAT({1}, '%Y-%m-%d')",
                        dto.getParams().get("beginCreateTime"),
                        dto.getParams().get("endCreateTime")));


        PageResult pageResult = new PageResult();
        pageResult.setCode(200);
        pageResult.setTotal((int) p.getTotal());
        pageResult.setRows(p.getRecords());
        pageResult.setMsg("认证成功");
        return pageResult;
    }

    //捞取商机
    @Override
    public void pull(PullDto dto) {
        List<Business> businesses = businessMapper.selectList(Wrappers.<Business>lambdaQuery()
                .in(Business::getId, dto.getIds()));
        businesses.forEach((i)->{
            i.setAuthenticity(T);
            i.setStatus(TRUE);
            i.setOwner("admin");
        });
        super.updateBatchById(businesses);
    }
//按照名字分类查询数量
    @Override
    public Map<String, Long> selectCount() {
        QueryWrapper<Business> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("owner", "count(*) as Businesscount");
        queryWrapper.groupBy("owner");

        List<Map<String, Object>> result = businessMapper.selectMaps(queryWrapper);
//        转换成Map集合
        Map<String, Long> businessresult = result.stream()
                .collect(Collectors.toMap(
                        map -> (String) map.get("owner"),
                        map -> (Long) map.get("Businesscount")
                ));

        log.info("何煜的方法");
        return businessresult;

    }

    /**
     * 辅助方法
     */
    private boolean hasDateRange(BusinessPageDto dto) {
        return ObjectUtils.isNotEmpty(dto.getParams()) &&
                ObjectUtils.isNotEmpty(dto.getParams().get("beginCreateTime")) &&
                ObjectUtils.isNotEmpty(dto.getParams().get("endCreateTime"));
    }

    /**
     * 辅助方法
     */
    private boolean DateRange(BusinessFalsePageDto dto) {
        return ObjectUtils.isNotEmpty(dto.getParams()) &&
                ObjectUtils.isNotEmpty(dto.getParams().get("beginCreateTime")) &&
                ObjectUtils.isNotEmpty(dto.getParams().get("endCreateTime"));
    }
}
